import 'package:mobx/mobx.dart';
import '../models/team_model.dart';
import '../services/team_service.dart';
import 'auth_store.dart';

part 'team_store.g.dart';

class TeamStore = _TeamStore with _$TeamStore;

abstract class _TeamStore with Store {
  final TeamService _teamService = TeamService();
  final AuthStore _authStore;

  _TeamStore(this._authStore);

  @observable
  ObservableList<TeamModel> teams = ObservableList<TeamModel>();

  @observable
  bool isLoading = false;

  @observable
  String? errorMessage;

  @observable
  TeamModel? selectedTeam;

  @computed
  List<TeamModel> get userTeams {
    if (_authStore.currentUser == null) return [];
    return teams
        .where((team) => team.memberIds.contains(_authStore.currentUser!.id))
        .toList();
  }

  @computed
  List<TeamModel> get createdTeams {
    if (_authStore.currentUser == null) return [];
    return teams
        .where((team) => team.initiatorId == _authStore.currentUser!.id)
        .toList();
  }

  @action
  Future<void> loadTeams() async {
    isLoading = true;
    errorMessage = null;

    try {
      final loadedTeams = _teamService.getAllTeams();
      teams.clear();
      teams.addAll(loadedTeams);
      isLoading = false;
    } catch (e) {
      errorMessage = 'Load teams failed: ${e.toString()}';
      isLoading = false;
    }
  }

  @action
  Future<TeamModel?> createTeam({
    required String name,
    required DateTime departureDate,
    required int maxMembers,
    String description = '',
    required String backgroundImage,
  }) async {
    if (_authStore.currentUser == null) return null;

    isLoading = true;
    errorMessage = null;

    try {
      final newTeam = await _teamService.createTeam(
        name: name,
        initiatorId: _authStore.currentUser!.id,
        departureDate: departureDate,
        maxMembers: maxMembers,
        description: description,
        backgroundImage: backgroundImage,
      );

      teams.add(newTeam);
      isLoading = false;
      return newTeam;
    } catch (e) {
      errorMessage = 'Create team failed: ${e.toString()}';
      isLoading = false;
      return null;
    }
  }

  @action
  Future<bool> joinTeam(String teamId) async {
    if (_authStore.currentUser == null) return false;

    isLoading = true;
    errorMessage = null;

    try {
      final success = await _teamService.joinTeam(
        teamId,
        _authStore.currentUser!.id,
      );

      if (success) {
        await loadTeams(); // 重新加载以获取更新后的团队
      }

      isLoading = false;
      return success;
    } catch (e) {
      errorMessage = 'Join team failed: ${e.toString()}';
      isLoading = false;
      return false;
    }
  }

  @action
  Future<bool> leaveTeam(String teamId) async {
    if (_authStore.currentUser == null) return false;

    isLoading = true;
    errorMessage = null;

    try {
      final success = await _teamService.leaveTeam(
        teamId,
        _authStore.currentUser!.id,
      );

      if (success) {
        await loadTeams(); // 重新加载以获取更新后的团队
      }

      isLoading = false;
      return success;
    } catch (e) {
      errorMessage = 'Leave team failed: ${e.toString()}';
      isLoading = false;
      return false;
    }
  }

  @action
  void selectTeam(String teamId) {
    selectedTeam = teams.firstWhere((team) => team.id == teamId);
  }
}
